package cn.cqautotest.cqviehelper.base;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Process;
import android.util.Log;

import com.blankj.utilcode.util.Utils;
import com.hjq.bar.TitleBar;
import com.hjq.bar.style.TitleBarLightStyle;
import com.hjq.http.EasyConfig;
import com.hjq.http.config.IRequestServer;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.smtt.sdk.QbSdk;
import com.vondear.rxtool.RxTool;
import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;

import java.util.List;

import cat.ereza.customactivityoncrash.config.CaocConfig;
import cn.cqautotest.cqviehelper.config.AppConfig;
import cn.cqautotest.cqviehelper.presenter.CoursePresenter;
import cn.cqautotest.cqviehelper.skin.SkinManager;
import cn.cqautotest.cqviehelper.ui.activity.CrashActivity;
import cn.cqautotest.cqviehelper.ui.activity.HomeActivity;
import cn.cqautotest.cqviehelper.utils.ActivityManager;
import cn.cqautotest.cqviehelper.utils.network.model.RequestHandler;
import cn.cqautotest.cqviehelper.utils.network.server.ReleaseServer;
import cn.cqautotest.cqviehelper.utils.network.server.TestServer;
import cn.cqautotest.micalendar.utils.CalendarEventUtils;
import okhttp3.OkHttpClient;

@SuppressLint("StaticFieldLeak")
public class BaseApplication extends Application {

    // 此TAG在adb logcat中检索自己所需要的信息， 只需在命令行终端输入 adb logcat | grep
    // cn.cqautotest.classschedulepush
    public static final String TAG = BaseApplication.class.getName();
    // user your appid the key.
    private static final String APP_ID = "2882303761518574762";
    // user your appid the key.
    private static final String APP_KEY = "5621857483762";
    private static Context sContext = null;
    private static Handler sHandler = null;

    @Override
    public void onCreate() {
        super.onCreate();
        sContext = this;
        sHandler = new Handler();
        initCourseData();
        initSDK();
        initOther();
    }

    private void initOther() {
        CalendarEventUtils.init(this);
    }

    private void initCourseData() {
        CoursePresenter coursePresenter = CoursePresenter.getInstance();
       // SharedPreferences spUserInfoSetting = getSharedPreferences(Constants.USER_INFO_SETTING, Context.MODE_PRIVATE);
       // String userId = spUserInfoSetting.getString(Constants.USER_ID, "");
       // String schoolYear = spUserInfoSetting.getString(Constants.SCHOOL_YEAR, "2020-2021");
       // int term = spUserInfoSetting.getInt(Constants.TERM, 1);
       // coursePresenter.getCourseByWeek(userId, schoolYear, term, term);
    }

    private void initSDK() {
        // 注册push服务，注册成功后会向DemoMessageReceiver发送广播
        // 可以从DemoMessageReceiver的onCommandResult方法中MiPushCommandMessage对象参数中获取注册信息
        if (shouldInit()) {
            MiPushClient.registerPush(this, APP_ID, APP_KEY);
        }
        LoggerInterface newLogger = new LoggerInterface() {

            @Override
            public void setTag(String tag) {
                // ignore
            }

            @Override
            public void log(String content, Throwable t) {
                Log.d(TAG, content, t);
            }

            @Override
            public void log(String content) {
                Log.d(TAG, content);
            }
        };
        Logger.setLogger(this, newLogger);
        //初始化换肤管理器
        SkinManager.getInstance().init(this);
        RxTool.init(this);
        Utils.init(this);
        // 标题栏全局样式
        TitleBar.initStyle(new TitleBarLightStyle(this));
        // Crash 捕捉界面
        CaocConfig.Builder.create()
                //后台模式
                .backgroundMode(CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM)
                //启用
                .enabled(true)
                //追踪活动
                .trackActivities(true)
                .minTimeBetweenCrashesMs(2000)
                // 重启的 Activity
                .restartActivity(HomeActivity.class)
                // 错误的 Activity
                .errorActivity(CrashActivity.class)
                // 设置监听器
                //.eventListener(new YourCustomEventListener())
                .apply();
        // 设置全局的 Header 构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> new ClassicsHeader(context).setEnableLastTime(false));
        // 设置全局的 Footer 构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> new ClassicsFooter(context).setDrawableSize(20));
        // Activity 栈管理初始化
        ActivityManager.getInstance().init(this);
        RxTool.getBackgroundHandler().post(() -> {
            // 网络请求框架初始化
            IRequestServer server;
            if (AppConfig.isDebug()) {
                server = new TestServer();
            } else {
                server = new ReleaseServer();
            }
            EasyConfig.with(new OkHttpClient())
                    // 是否打印日志
                    .setLogEnabled(AppConfig.isDebug())
                    // 设置服务器配置
                    .setServer(server)
                    // 设置请求处理策略
                    .setHandler(new RequestHandler(this))
                    // 设置请求重试次数
                    .setRetryCount(3)
                    // 添加全局请求参数
                    //.addParam("token", "6666666")
                    // 添加全局请求头
                    //.addHeader("time", "20191030")
                    // 启用配置
                    .into();
            preInitX5WebCore();
            //初始化X5浏览器内核环境
            QbSdk.initX5Environment(getContext(), null);
        });
    }

    private boolean shouldInit() {
        android.app.ActivityManager am = ((android.app.ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<android.app.ActivityManager.RunningAppProcessInfo> processInfos = null;
        if (am != null) {
            processInfos = am.getRunningAppProcesses();
        }
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        if (processInfos != null) {
            for (android.app.ActivityManager.RunningAppProcessInfo info : processInfos) {
                if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                    return true;
                }
            }
        }
        return false;
    }

    private void preInitX5WebCore() {
        if (!QbSdk.isTbsCoreInited()) {
            QbSdk.preInit(this, null);// 设置X5初始化完成的回调接口
        }
    }

    public static void reInitPush(Context ctx) {
        MiPushClient.registerPush(ctx.getApplicationContext(), APP_ID, APP_KEY);
    }

    public static Handler getHandler() {
        return sHandler;
    }

    public static Context getContext() {
        return sContext;
    }
}
